#!groovy

@Library('jenkinslib@master') _

//func from shareibrary
def dingmes  = new org.devops.ding()
def build = new org.devops.build()
def deploy = new org.devops.deploy()
def tools = new org.devops.tools()
def gitlab = new org.devops.gitlab()
def toemail = new org.devops.toemail()
def sonar = new org.devops.sonarqube()
def sonarapi = new org.devops.sonarapi()
def nexus = new org.devops.nexus()
def artifactory = new org.devops.artifactory() 
def k8s = new org.devops.kubernetes()
def model = new org.devops.modules()
def mvn_com  = "/usr/bin/mvn"
def workdir = ''
def pronames = ''
def harbor_name = ''
// def runOpts
//env
String buildType = "${env.buildType}"
//编译脚本
String buildShell = "${env.buildShell}"
//部署的环境
String deployHosts = "${env.deployHosts}"
//gitlab仓库地址
String srcUrl = "${env.srcUrl}"
//仓库分支
String branchName = "${env.branchName}"
//微服务名称
String proName = "${env.proName}"
//项目名称
String proJectname = "${env.project}"
//容器端口
String port = ""
//pipeline
pipeline{
    agent any    
    stages{

       stage("GetCode"){
            steps{
                script{
                        workdir = srcUrl.split('/')[-1].split('.git')[0]
                        if(!workdir) {
                            println "获取工作目录失败"
                            exit()
                        }
                        tools.PrintMes("获取代码","green")
                        checkout([$class: 'GitSCM', branches: [[name: "${branchName}"]], 
                        doGenerateSubmoduleConfigurations: false, 
                        extensions: [[$class: 'RelativeTargetDirectory', relativeTargetDir: "${workdir}"]], 
                        submoduleCfg: [], 
                        userRemoteConfigs: [[credentialsId: '87886427-ebc2-4f45-8921-dcf38f80867e', url: "${srcUrl}"]]])
                }
            }
        }
        /*
        stage('SonarQube analysis') {
            steps {
                script {
                    tools.PrintMes("开始代码检查","green")
                    withSonarQubeEnv('SonarQube') {
                    // Optionally use a Maven environment you've configured already
                    sh "cd ${workdir} && cd ${proName} && ${mvn_com} sonar:sonar -Dsonar.projectKey=helloworld -Dsonar.java.binaries=target/sonar  -Dsonar.host.url=http://172.16.1.108:9000 -Dsonar.login=3fc0c5d905cd0fa0c32ec9f7dab0f71c5ccb7964"
                  }
                }
            }
        }
        stage("Quality Gate") {
            steps {
                script {
                    sleep(15)
                    // Parameter indicates whether to set pipeline to UNSTABLE if Quality Gate fails
                    // true = set pipeline to UNSTABLE, false = don't
                     //   waitForQualityGate abortPipeline: true
                        def qg = waitForQualityGate()
                        if (qg.status != 'OK') {
                            echo("代码检查没有通过 ❌")
                            failure
                        }
                        echo("代码检查通过😄  😄  ")
                    }
                }
            }
        */
        stage("Build&Test"){
            steps{
                script{
                    tools.PrintMes("修改bootstrap文件","green")
	      //修改nacos服务端地址
                     sh "sed -i 's/server-addr.*/server-addr: \${NACOS_HOST}:\${NACOS_PORT}/' ${workdir}/${proName}/src/main/resources/bootstrap.yml"
                     //修改用户名
	      sh "sed -i 's/username:.*/username: \${NACOS_USER}/' ${workdir}/${proName}/src/main/resources/bootstrap.yml"
	      //修改密码
                     sh "sed -i 's/password:.*/password: \${NACOS_PASSWD}/' ${workdir}/${proName}/src/main/resources/bootstrap.yml"
	      //获取端口号
                     res = sh returnStdout: true ,script: "grep 'port:' ${workdir}/${proName}/src/main/resources/bootstrap.yml |awk -F':' '{print \$2}'"
                     port = res.trim()
                    tools.PrintMes("执行打包","green")
                    sh "cd ${workdir} && cd ${proName} && ${buildShell}"
                    sh "exit 0"
                }
            }
       }
       //构建镜像&&上传
        stage("BuildImages"){
            steps{
                script{
                    tools.PrintMes("下载Dockfile","green")
                    dockerinfo = model.dockfile(port)
                    writeFile(file: "${workdir}/${proName}/Dockerfile", text: "${dockerinfo} ", encoding: "UTF-8")
                    tools.PrintMes("构建上传镜像","green")
                    def HARBOR_URL = "harbor.ebcall.com"
                    def username = "admin"
                    def password = "cfXoldg71ODYhqnT"
                    result = sh returnStdout: true ,script: "cd ${workdir} && cd ${proName} && git describe --tags"
                    result = result.replace('\n','')
                    result = result.trim()
                    if (!result){
                        println '当前分支无tag标签'
                    }
                    //判断./情况
                    pronames = model.pronames(proName,workdir)
                    harbor_name = "${HARBOR_URL}/${proJectname}/${pronames}:${result}"
                    sh """
                        cd ${workdir}
                        cd ${proName}
                        docker login -u ${username} -p ${password}  ${HARBOR_URL}
                        sleep 1
                        docker build -t ${HARBOR_URL}/${proJectname}/${pronames}:`git describe --tags` .
                        sleep 1
                        docker push ${HARBOR_URL}/${proJectname}/${pronames}:`git describe --tags`
                        sleep 1
                        docker rmi ${HARBOR_URL}/${proJectname}/${pronames}:`git describe --tags`
                      """
                    }
                }
            }
        //部署检测
        stage("k8s_check"){
            steps{
                script{
                    tools.PrintMes("检测存在状态","green")
                      //deployment status
                      result = k8s.GetDeployment(proJectname,pronames)
                      if (result != '0') {
                            println 'update'
                            k8s.UpdateDeployment(proJectname,pronames,model.deployment(pronames,harbor_name,proJectname,port))
                            println 'update 完成'
                      }else {
                            tools.PrintMes("发布应用测试","green")
                            //修改deployment文件
                            //proName
                            result = model.deployment(pronames,harbor_name,proJectname,port)
                            //deployment创建
                            k8s.CreateDeployment("${proJectname}","null",result)
                            sleep 5
                            result = model.Services(pronames,proJectname,port)
                            //服务创建
                            k8s.CreateServices("${proJectname}",pronames,result)
                            //获取Service
                            result = k8s.GetServices("${proJectname}",pronames)
                      }
                    }
                }
            }
        }
        post{
            success{
                script{
                    tools.PrintMes("========pipeline executed successfully========",'green')
                    dingmes.HttpReq(pronames,'null',"构建成功 ✅ ")
                }
            }
            failure{
                script{
                    tools.PrintMes("========pipeline execution failed========",'red')
                    dingmes.HttpReq(pronames,'null',"构建失败 ❌","请查看控制台")
                }
            }
            unstable{
                script{
                    tools.PrintMes("========pipeline execution unstable========",'red')
                    dingmes.HttpReq(pronames,'null',"构建失败 ❌","不稳定异常")
                }
            }
            aborted{
                script{
                    tools.PrintMes("========pipeline execution aborted========",'blue')
                    dingmes.HttpReq(pronames,ImageTag,"构建失败 ❌","暂停或中断")
                }
            }
        }
}
